
class VideosController < ApplicationController

	STATUS_LABELS = VideoStatus.find(:all, :order => 'id').collect {|s| s.name}.unshift ''

	def index
		@showThumbs			= Conf.ShowThumbs == '1'
		@imgUrl					= NetflixClient::THUMBS_URL
		@title					= 'Videos'
		@statusLabels		= STATUS_LABELS
		@serverStatus,	= try_status

		# Parse sort
		@order = cookies[:order]
		if not @order =~ /^(Title|Status|Size) (ASC|DESC)$/
			@order = 'Title ASC'
		end

		@orderCol, @orderDir = @order.split(' ')

		opts = (@orderCol == 'Title') ? {:order => @order} : nil
		@videos = Video.find(:all, opts)
	end

	# ==========
	# AJAX methods
	# ==========

	# Retrieve server status
	def status
		logger.silence {
			render :json => try_status.to_json
		}
	end

	# Render a single video row
	def video
		ids = params[:id]

		@videos = Video.find_by_nf_id(ids.split(','))
		@videos = [@videos] if not @videos.is_a?(Array)
		@imgUrl = NetflixClient::THUMBS_URL
		@showThumbs = Conf.ShowThumbs == '1'

		result = ''

		@videos.each {|v|
			result += render_video(v, @showThumbs)
		}

		render :text => result
	end

	# Delete a video
	def delete_video
		id = params[:id]

		v = Video.find_by_nf_id(id)

		# Delete it!
		File.delete(v.file_name)

		v.status_id = VideoStatus::DELETED
		v.save

		render :text => render_video(v)
	end

	# Retry video
	def retry_video
		id = params[:id]

		v = Video.find_by_nf_id(id)
		v.status_id = VideoStatus::DOWNLOADING
		v.save

		render :text => render_video(v)
	end

	# Forwards to Netfluxd
	def server_start
		result = NetfluxdClient.new.start.to_json
		Conf.ServerRunning = '1'
		render :json => result
	end

	def server_shutdown
		result = NetfluxdClient.new.shutdown.to_json
		Conf.ServerRunning = nil
		render :json => result
	end

	def server_check
		render :json => NetfluxdClient.new.queue.to_json
	end

protected
	def try_status
		# Compute current file size
		current = Video.find(:all, :conditions => ['status_id = ?', VideoStatus::DOWNLOADING])

		sizes = current ? current.map {|v|
			[
				v.nf_id,
				File.exists?(v.file_name) ? VideosHelper.format_bytes(File.size(v.file_name)) : 'missing'
			]
		} : []

		# Get netfluxd status
		serverStatus = Conf.ServerRunning ? NetfluxdClient.new.status : 'stopped'

		[serverStatus, sizes]
	end

	def render_video(v, showThumbs = nil)
		showThumbs ||= Conf.ShowThumbs == 1

		render_to_string({
			:partial	=> 'video',
			:object	 => v,
			:locals	 => {
				:imgUrl			 => NetflixClient::THUMBS_URL,
				:showThumbs	 => showThumbs,
				:statusLabels => STATUS_LABELS
			}
		})
	end

end
